﻿using EasyNetQ;
using EasyNetQTest.Message;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Topshelf.MQ.Revice
{
    public class MyService
    {
        //List<IBus> busList = new List<IBus>();
        int delay = 500;
        IBus bus;

        /// <summary>
        /// 服务启用
        /// </summary>
        public void Start()
        {
            var connStr = "host=192.168.0.248;username=admin;password=admin";

            int pocCount = 10;
            //连接MQ
            bus = RabbitHutch.CreateBus(connStr);
            //创建10个消息费者来同时处理消息
            for (int i = 0; i < pocCount; i++)
            {

                //busList.Add(bus);
                //异步执行消息处理任务
                Task.Run(() =>
                {
                    doWork(bus, i.ToString());
                });
            }
        }

        //服务结束
        public void Stop()
        {
            //服务结束时，Dispose
            //busList.ForEach(o => o.Dispose());
            bus.Dispose();
        }

        /// <summary>
        /// 消息处理方法
        /// </summary>
        /// <param name="bus"></param>
        /// <param name="busName"></param>
        public void doWork(IBus bus, string busName)
        {
            //直接从队列中接收消息
            bus.SendReceive.Receive<MyMessage>("Test.TestQueue2", o =>
            {
                Console.WriteLine(busName + ",收到消息: {0}", o.MsgContent);

                Thread.Sleep(delay);//模拟耗时,进行消息处理                        
                Console.WriteLine(busName + $",{o.MsgId}处理结束\n");
            });
        }
    }
}
